// 引入必备文件吧。我也不知道怎么解释引入了啥。
const { json } = require('express');
let express = require('express');
let router = express.Router();
let homeModel = require('../db/homeDb');

// 新增/编辑数据
router.post('/save', (req, res) => {
    let param = req.body;
    // 如果存在GUID就是编辑
    if (param.guidCode) {
        homeModel.update({ guidCode: param.guidCode }, param, { multi: true }, (err, data) => {
            let resData = {
                isOk: true
            };
            if (err) {
                resData = {
                    isOk: false,
                    msg: err
                };
            }
            res.json({ resData });
        })
    }
    // 否则就是新增
    else {
        param.guidCode = guid();
        homeModel.create(param, (err, data) => {
            let resData = {
                isOk: true
            };
            if (err) {
                resData = {
                    isOk: false,
                    msg: err
                };
            }
            res.json({ resData });
        })
    }
})


// 删除数据
router.post('/delete', (req, res) => {
    let param = { "guidCode": req.body };
    homeModel.remove(param, (err, data) => {
        let resData = {
            isOk: true
        };
        if (err) {
            resData = {
                isOk: false,
                msg: err
            };
        }
        res.json({ resData });
    })
})

// 查询数据
router.post('/list', (req, res) => {
    // 当前第几页
    let page = parseInt(req.body.page);
    // 一页多少条
    let pageSize = parseInt(req.body.pageSize);
    // 查询条件 - 固定
    // let keyword = {'bbDesc':req.body.keyword};
    // 查询条件 - 模糊
    let keyword = { 'bbDesc': { $regex: req.body.keyword, $options: 'i' } };
    // 排序（按创建时间倒序)
    let sort = { 'createTime': -1 };
    // 跳过数
    let skipnum = (page - 1) * pageSize;   //跳过数  
    // 用于获取数据总条数
    homeModel.count({}, (err, count) => {
        let total = count;
        homeModel.find(keyword).skip(skipnum).limit(pageSize).sort(sort).exec((err, data) => {
            let resData = {};
            if (err) {
                // console.log(err);
                resData = {
                    isOk: false,
                    msg: err
                }
            } else {
                // console.log(res);
                resData = {
                    isOk: true,
                    data,
                    total
                }
                res.json({ ...resData });
            }
        })
    })
})




// 生成GUID
function guid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        }
    );
};




module.exports = router;